package com.jgads.ad.sdk.mediation.adapter;

import android.content.Context;
import android.util.Log;
import android.view.ViewGroup;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.splash.MediationCustomSplashLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.jgads.ad.sdk.mediation.utils.ThreadUtils;
import com.junion.ad.BidLossNotice;
import com.junion.ad.SplashAd;
import com.junion.ad.bean.SplashAdInfo;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.SplashAdListener;

import java.util.Map;

/**
 * @Description:
 * @Author: maipian
 * @CreateDate: 12/23/21 6:11 PM
 */
public class CustomerSplashAdapter extends MediationCustomSplashLoader {

    private SplashAd splashAd;
    private SplashAdInfo splashAdInfo;

    @Override
    public void load(final Context context, AdSlot adSlot, final MediationCustomServiceConfig serviceConfig) {

        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                splashAd = new SplashAd(context);
                splashAd.setListener(new SplashAdListener() {
                    @Override
                    public void onAdTick(long millisUntilFinished) {
                    }

                    @Override
                    public void onAdReceive(SplashAdInfo adInfo) {
                        splashAdInfo = adInfo;

                        if (isClientBidding() && adInfo != null) {//bidding广告类型
                            //bidding广告成功回调，回传竞价广告价格 单位：分
                            callLoadSuccess(adInfo.getBidPrice());
                        } else {
                            //普通广告成功回调
                            callLoadSuccess();
                        }
                    }

                    @Override
                    public void onAdExpose(SplashAdInfo adInfo) {
                        callSplashAdShow();
                    }

                    @Override
                    public void onAdClick(SplashAdInfo adInfo) {
                        callSplashAdClicked();
                    }

                    @Override
                    public void onAdSkip(SplashAdInfo adInfo) {
                        callSplashAdSkip();
                    }

                    @Override
                    public void onAdClose(SplashAdInfo adInfo) {
                        callSplashAdDismiss();
                    }

                    @Override
                    public void onAdFailed(JUnionError error) {
                        callLoadFail(error.getCode(), error.getError());
                    }
                });

                if (serviceConfig != null) {
                    splashAd.loadAd(serviceConfig.getADNNetworkSlotId());
                }
            }
        });

    }

    @Override
    public MediationConstant.AdIsReadyStatus isReadyCondition() {
        if (splashAdInfo != null && !splashAdInfo.isOvertime()) {
            return MediationConstant.AdIsReadyStatus.AD_IS_READY;
        } else {
            if (splashAdInfo != null && splashAdInfo.isOvertime()) {
                return MediationConstant.AdIsReadyStatus.AD_IS_EXPIRED; // 注意这里是AD_IS_EXPIRED
            }
            return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
        }
    }

    /**
     * show在主线程中回调
     */
    @Override
    public void showAd(final ViewGroup viewGroup) {
        Log.i(Const.TAG, "showAd");
        if (splashAdInfo != null && viewGroup != null) {

            //先showAd，防止没有上报bidWin事件导致广告无法正常使用
            if (isClientBidding() && !splashAdInfo.isReportBidWin()) {
                splashAdInfo.sendWinNotice((int) splashAdInfo.getBidPrice());
            }

            viewGroup.addView(splashAdInfo.getSplashAdView(),
                    new ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT)
            );

            splashAdInfo.render();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (splashAd != null) {
            splashAd.release();
            splashAd = null;
        }
        if (splashAdInfo != null) {
            splashAdInfo.release();
            splashAdInfo = null;
        }
    }

    /**
     * @param win         是否在本次竞价中获胜
     * @param winnerPrice 获胜者价格，可能为0 ,如果没有胜出则该值是-1
     * @param loseReason  竞价失败原因 1:价格较低 2：广告返回超时 10001：其他；如果胜出则该值是-1
     * @param extra       扩展参数
     */
    @Override
    public void receiveBidResult(boolean win, double winnerPrice, int loseReason, Map<String, Object> extra) {
        Log.i(Const.TAG, "receiveBidResult   win = "+ win+"  "+
                "winnerPrice = "+winnerPrice +"  "+
                "loseReason = " +loseReason  +"  "+
                Thread.currentThread().toString());
        if (win) {
            //竞价成功  showAd回调可能会先触发，防止重复上报BidWin
            if (splashAdInfo != null && !splashAdInfo.isReportBidWin()) {
                splashAdInfo.sendWinNotice((int) winnerPrice);
            }
        } else {
            //竞价失败
            if (splashAdInfo != null) {
                if (loseReason == 1) {
                    splashAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.LOW_PRICE);
                } else {
                    splashAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.OTHER);
                }
            }
        }
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }

}
